package com.yy.cleaner.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.cleaner.common.BaseReponse;
import com.yy.cleaner.constant.RedisConstant;
import com.yy.cleaner.mapper.UserMapper;
import com.yy.cleaner.model.dto.UserLoginRequest;
import com.yy.cleaner.model.pojo.LoginUser;
import com.yy.cleaner.model.pojo.User;
import com.yy.cleaner.service.UserService;
import com.yy.cleaner.utils.JwtUtil;
import com.yy.cleaner.utils.RedisCache;
import com.yy.cleaner.utils.ReponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    /**
     * 用户登录
     */
    @Override
    public HashMap userLogin(UserLoginRequest loginRequest) {
        //2.进行security 用户鉴权
        //todo 了解authenticationManager.authenticate 底层用了什么技术查询了数据库
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginRequest.getUserName(),loginRequest.getPassWord());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //3.鉴权通过 使用userid生成jwt 并把用户信息存入redis 然后把token响应给前端
        //存入redis 原因：
        //如果每次非登录操作都要根据userid获取用户信息 对数据库压力太大了
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //开始生成jwt
        //获取userid
        LoginUser loginUser =(LoginUser) authenticate.getPrincipal();
        User user = loginUser.getUser();
        String userId = new Integer(user.getUserId()).toString();
        String jwt = JwtUtil.createJWT(userId,RedisConstant.EXPIR_TIME);
        log.info("生成的token为:"+jwt);
        //把用户信息存入redis
        redisCache.setCacheObject(RedisConstant.LOGIN_USER_REDIS_PRE +userId,user);
        //响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);
        return map;
    }


    /**
     * 退出登录
     */
    @Override
    public void userLoginOut() {
        //1.从security中获取到 userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        int userId = user.getUserId();
        //2.清除redis存储的用户数据
        //当清除之后 其他操作在通过jwt过滤器时因为找不到用户信息而得不到授权 自然无法进行操作
        //清除
        redisCache.deleteObject(RedisConstant.LOGIN_USER_REDIS_PRE+userId);
        log.info("清除token成功 退出登录");
    }


}
